
var sd = new Date();

(function (o, config) {


                    o.write('<div id="message"></div>');
                    o.write('<div class="progress-bar">');
                    o.write('<div id="bar"></div></div><br>');
                    o.write('<div id="tag_cloud"><div id="loading_tag_cloud"></div><ul id="tag_list"></ul></div>');
                    o.write('<div id="postpanels"></div>');


var tag_count=0;



	var switcher = $('<a href="javascript:void(0)" class="btn">Change appearance</a>').toggle(
		function(){
			$("#tag_cloud ul").hide().addClass("alt").fadeIn("fast");
		},
		function(){
			$("#tag_cloud ul").hide().removeClass("alt").fadeIn("fast");
		}
	);
 	$('#sortlinks').append(switcher);

	var sortabc = $('<a href="javascript:void(0)" class="btn">Sort alphabetically</a>').toggle(
		function(){
			$("#tag_list ul li").tsort({order:"asc"});
		},
		function(){
			$("#tag_list ul li").tsort({order:"desc"});
		}
		);
 	$('#sortlinks').append(sortabc);

	var sortstrength = $('<a href="javascript:void(0)" class="btn">Sort by useage</a>').toggle(
		function(){
			$("#tag_cloud ul li").tsort({order:"desc",attr:"title"});
		},
		function(){
			$("#tag_cloud ul li").tsort({order:"asc",attr:"title"});
		}
		);
 	$('#sortlinks').append(sortstrength);




    
    function loadmore(filename, filetype) {
        debug(1, "loading external " + filetype + " file."
        );
        if (filetype == "js") { //if filename is a external JavaScript file
            fileref = document.createElement('script')
            fileref.setAttribute("type", "text/javascript")
            fileref.setAttribute("src", filename)
        }
        else if (filetype == "css") { //if filename is an external CSS file
            fileref = document.createElement("link")
            fileref.setAttribute("rel", "stylesheet")
            fileref.setAttribute("type", "text/css")
            fileref.setAttribute("href", filename)
        }
        if (typeof fileref != "undefined")
            document.getElementsByTagName("head")[0].appendChild(fileref)
    }

  

    function debug(lvl,text,that)
    {

         if (!debugging) { return; }

        $("#bar").html("" + text + "");
        var msg = "MSG:" + text + "\n From: "+arguments.callee.caller.name;

        if (window.console.firebug) {
            switch (lvl) {
                case 0:
                    console.log(msg);
                    break;
                case 1:
                    console.info(msg);
                    break;
                case 2:
                    console.warn(msg);
                    break;
                case 3:
                    console.warn(msg);
                    break;
                case 4:
                  default:
                     console.log(msg);
            }
        }
        else if (typeof(window.console != "undefined")) {
            console.log(msg);
        }
        lastcaller = that;
    }

    function f(i) {
        return typeof (i) !== "undefined";
    }

    function p(q, i) {
        return (q - i);
    }

    function m(i, q) {
        return i.sort(function (s, r) {
            return q[s] - q[r];
        });
    }

    function c(r) {
        var i = [];
        var q;
        for (q in r) {
            if (r.hasOwnProperty(q)) {
                i.push(q);
            }
        }
        return i;
    }

    function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

        /*for (var i = 0; i < hashes.length; i++) {
         hash = hashes[i].split('=');
         var params = "hash# " + i + " value is [" + hash + "]";
         */
        for (l = 0; l < hashes.length; l++) {
            var k = hashes[l].split("=");
            config[k[0]] = unescape(k[1]);
        }
        debug(2, "config=" + config, this);
        console.dir(config);
    }



function getEpochdate(edate)
{
var myDate = new Date( edate *1000);
//myDate.toGMTString()
        return(myDate.toLocaleString());
}
    var count;
    var postsout=0;
    if (typeof(window.console.firebug != "undefined"))
    { var firebugcon=true;}
    var debugging = true;
    var config = {};
    var g = o.getElementsByTagName("script");
    var a = g[g.length - 1];
    var e = a.src.replace(/^[^\?]+\??/, "").split("&");
    var l = 0;
    var postcount = 0;
    var tag_count = 0;
    var cssurl = "";
    var taglist = new Array;
    var tagblob = new Object;
    var totalposts;
    loadmore('TumblrAPIconfig.js','script'); // load the api config file automatically.

/* read config parameters from the script call
* these will over write the config file setting*/

    for (l = 0; l < e.length; l++) {
        var k = e[l].split("=");
        config[k[0]] = unescape(k[1]);
    }

    if (!f(config.minsize)) {
        config.minsize = 100;
    }    if (!f(config.show)) {
        config.show = 'taglist';
    }
    if (!f(config.maxsize)) {
        config.maxsize = 200;
    }
    if (!f(config.math)) {
        config.math = "log";
    }
    if (!f(config.type)) {
        config.type = "photo";
    }
    if (!f(config.apikey)) {
        config.apikey = 'PyezS3Q4Smivb24d9SzZGYSuhMNPQUhMsVetMC9ksuGPkK1BTt';
    }
    if (!f(config.apilimit)) {
        config.apilimit = 20;
    }
    if (!f(config.apiurl)) {
        config.apiurl = "api.tumblr.com";
    }
    if(!f(config.num)){
        config.num=5;
    }
    var h = (!f(config.url)) ? o.domain : config.url;

    var j = "http://"+h+"/";
    var blogurl = "http://"+h+"/";


    if (typeof(config.classname) == 'undefined') {
        config.classname = "tag_item";
    }
    if (typeof(config.size)=="undefined"){config.size="100";}

    switch (config.css) {
        case ('default'):
            cssurl = 'default.css';
            break;
        case ('flickr'):
            cssurl = 'default.css';
            break;
        case ('tumblr'):
            cssurl = '"tumlr.css';
            break;
        case ('custom'):

            cssurl = "";
            break;
    }
    var n = "" + cssurl + "";

    loadmore(cssurl, "css");
    ;


    $(o).ready(function () {
        var u = 0;
        var q = [];
        var posttags = [];
        var i = [];
        var r = {};
        var tagcount = 0;
        var z = 0;
        var A = new Array;
    $("#bar").html("Loading tags");
    $("#bar-color").css("width", 10);//reset load bar to begining size


        function GetBloginfo(url)
        {
            debug(1,'Starting:getting blog info for: : '+url+'',this);

            var v='http://'+config.apiurl+'/v2/blog/'+config.url+'/info?api_key='+config.apikey+'&jsonp=?';
                $.getJSON(v, function (w) {
                 $(w.response.blog).each(function (y, item) {
                 var totallikes= item.likes;
                     totalposts = w.response.blog['posts'];'posts';
                     var output='blog: '+item.name+' has '+totalposts+'posts and '+ totallikes+', Likes';

                     var bloginfo='blog title:'+item.title+
                     'last post was made on,'+getEpochdate(item.updated);
                     debug(2,bloginfo,this);
                    debug(2, output,this);
                 });
             })
        }


        function GetPostinfo(post) {
            if (postsout>=config.show);
            {return 0;}

            debug(3, "GetPostinfo," + post.id, this);
            /*Set Post Text*/
            var text = '';
            switch (post.type) {
                case 'text':
                    text += post['title'];
                    break;
                case 'link':
                    text += post['description'];
                    break;
                case 'chat':
                    text += post['body'];
                    break;
                case 'quote':
                    text += post['text'];
                    break;
                case 'photo':
                    text += post['caption'];
                    break;
                case 'video':
                    text += post['caption'];
                    break;
                case 'audio':
                    text += post['caption'];
                    break;
                case 'answer':
                    text += post['question'];
                    break;
            }
            /*Strip HTML from text*/
            var StrippedText = text.replace(/(<([^>]+)>)/ig, "");
            /*slice text to the desired length*/
            if (StrippedText.length > config.len) {
                StrippedText = StrippedText.slice(0, config.len);
                StrippedText += '...';
            }
            text = StrippedText;

            switch (post.type) {
                case 'text':
                    var fullbody = post.body;
                    var fullbodyset = $(fullbody);
                    image += fullbodyset.find('img').attr('src');
                    /*find images in text posts*/
                    break;
                case 'audio': /*find album art */
                    image += this.album_art;
                    break;
                case 'photo':
                $(post.photos[0]).each(function(i, photo) {
                    debug(2, "Photos: " + post.photos.length);
                    $(photo.alt_sizes).each(function(i, alt_size) {

                        if (config.size == '75' && alt_size.width == '75') {
                            image = alt_size['url'];
                        }
                        if (config.size == '100' && alt_size.width == '100') {
                            image = alt_size['url'];
                        }

                        if (config.size == '250' && alt_size.width == '250') {
                            image = alt_size['url'];
                        }
                        if (alt_size.width >> '500') {
                            debug(2, "HIREZ IMAGE DETECTED", this);
                        }
                        });
                    });
                    break;
                case 'link':
                var link = (post['url']);
                var title= (post['title']);
                break;
            }


            var link = (post['url']);


            /*Set Notes*/
            var note = 0;
            var notetext = "";
            note += post['note_count'];
            if (note == 'undefined'||note <<1) {
                note = '0';
            }

            if (note == 0) {
                notetext = 'Zero notes &hearts;';
            } else {
                notetext = "&hearts;" + (note === 1 ? note + " note " : note + " notes");
            }

            debug(1, "Post" + post.id + " type:" + post.type + "\nContent: " + text + "\n Post url:[" + link + "] notes: " + notetext);


        /* posts tags*/
        debug(2, "Post:" + post.id + " has " + post.tags.length + " tags: " + post.tags);
        $(post.tags).each(function (A, tag) {
            tagcount++;
            if (typeof (tag) === "string") {
                posttags.push(z);
            }
        });

        /*Print floating thumbnail for current post*/
        var content = '<a class="postlink" href="' + link + '" title="' + text + '"><img src="' + image + '" alt=""><div class="notes"></div><p>' + text + ' <span id="#notes" class="notes" style="display:inline">&hearts;' + note + '</span></p></a>';
        var output = '<div class="postbox">' + content + '</div>';
        $('#postpanels').append(output);

            postsout++;
    }


    function GetPostbyid(post_id)
        {

            debug(2,"Starting Getpostbyid: "+post_id);

             v = "http://api.tumblr.com/v2/blog/" + config.url + "/posts?api_key=" + config.apikey + "&id=" + post_id + "&jsonp=?";
             $.getJSON(v, function (w) {
                 $(w.response.posts).each(function (y, post) {
                     GetPostinfo(post);
                 });
             })
        }

        function GetPostbytags(tagged,count) {

            if (typeof(count) =="undefined"){
                count = config.num;
            }


            debug(3,"Get [" + count + "] Posts Tagged: ["+tagged+"]",this);
            
            var item = "";
            var offset = (Math.floor(Math.random() * totalposts)-count);
            var v;

            v = 'http://api.tumblr.com/v2/blog/' + config.url + '/posts?api_key=' + config.apikey + "&limit=" + count + '&tag=' + tagged + "&jsonp=?";
            $.getJSON(v, function (w) {
                 debug(3,"API Request Received ["+w.response.posts.length+']\nJSON= '+v);
                $(w.response.posts).each(function (y, post) {
                   new GetPostinfo(post);
                });

            })
        }


        function GetPosts() {

            $('#message').html("Loading Whole Tag List for : " + config.url);
            /*debug(1,"Starting, GetPosts");*/
            var v;
            v = "http://" + config.apiurl + "/v2/blog/" + config.url + '/posts?api_key=' + config.apikey + '&limit=' + config.apilimit + "&offset=" + u + '&type=' + config.type + '&jsonp=?';

            $.getJSON(v, function (w) {
                $("#bar").html(w.meta.status);
                $(w.response.posts).each(function (y, x) {
                    $(x.tags).each(function (A, z) {
                        tagcount++;
                        if (typeof (z) === "string") {
                            var Strippedtag = z.replace(/(<([^>]+)>)/ig,"");
                            q.push(z);
                        }
                    });
                });
                totalposts = w.response.blog['posts'];
                var recieved = w.response.posts.length;
                $("#message").html("Loaded:" + u + " posts.");

                if (u + recieved < totalposts) {
                    var x = parseInt(w.response.blog['posts']);
                    var y = parseInt(u);
                    var percentofis = CalculatePercent(u, x);
                    var barwidth = percentofis * 5;
                    $("#bar").html("" + percentofis + "%");
                    $("#bar").css("width", barwidth);
                    u = u + config.apilimit;
                    GetPosts();
                } else {
                    new ProcessTags();
                }
            });
        }

        function CalculatePercent(value, total) {
            return Math.round(100 * ( value / total ));
        }

        function ProcessTags() {
            debug(1, "Processing tags for:" + u + " posts out of" + totalposts + " posts for " + config.url,this);
            var A = {};
            var B = {};
            var x;
            var tag_count = 0;
            $(q).each(function (D, C) {
                r[C] = (r[C] ? r[C] + 1 : 1);
            });
            var w;

            for (w in r) {
                if (r.hasOwnProperty(w)) {
                    A[w] = r[w];
                    debug (2,"tag: "+w+" "+A[w]);
                }
            }

            if (config.math === "log") {
                for (w in r) {
                    if (r.hasOwnProperty(w)) {
                        r[w] = Math.log(r[w]);
                    }
                }
            }

            var v = c(r);
            var y;
            if (config.order === "frequency") {
                x = m(v, r).reverse();
                for (y in x) {
                    if (x.hasOwnProperty(y)) {
                        B[x[y]] = r[x[y]];
                    }
                }
                r = B;
            } else {
                if (config.order === "alphabetical") {
                    x = v.sort(function (D, F) {
                        var E = String(D).toUpperCase();
                        var C = String(F).toUpperCase();
                        if (E > C) {
                            return 1;
                        }
                        if (E < C) {
                            return -1;
                        }
                        return 0;
                    });
                    for (y in x) {
                        if (x.hasOwnProperty(y)) {
                            B[x[y]] = r[x[y]];
                        }
                    }
                    r = B;
                }
            }
            sizeRange = config.maxsize - config.minsize;
            var z;
            for (z in r) {
                if (r.hasOwnProperty(z)) {
                    i.push(r[z]);
                }
            }
            i.sort(p);
            minCount = i[0];
            maxCount = i[i.length - 1];
            slope = sizeRange / (maxCount - minCount);
            count = 0;
            var hiddentags = 0;
           /*loop thru all tags to generate the taglist*/
            for (w in r) {
                if (r.hasOwnProperty(w)) {
                    count++;
                    window.status = ("W " + w + "cnt" + count);

                    if (!f(config.limit) && config.limit !== "none" && count > config.limit) {
                       debug(3,"BREAKING",this);   break;
                    }
                     debug(3,"Wcontains["+w+"]",this);
                    GetPostbytags(w,2);/*Gets a few related posts  for each tag used*/
                        fontSize = Math.round(slope * r[w] - (slope * minCount - config.minsize));
                        title = (A[w] === 1 ? A[w] + " post" : A[w] + " posts");
                        postcount += A[w];
                        tag_count++;
                        var output = "";
                        switch (config.css) {
                            case ('default'):
                                link = '<a   style="font-size:' + fontSize + '%" href="' + blogurl + "tagged/" + w + '" title="' + title + '">' + w + "</a>";
                                output = '<li>' + link + '</li>';

                                break;
                            case ('flickr'):
                                link = '<a   style="font-size:' + fontSize + '%" href="' + blogurl + "tagged/" + w + '" title="' + title + '">' + w + "</a>";
                                output = '<li>' + link + '</li>';
                                break;
                            case ('related'):
                                link = '<a   style="font-size:' + fontSize + '%" href="' + blogurl + "tagged/" + w + '" title="' + title + '">' + w + "</a>";
                                output = '<li>' + link + '</li>';
                                break;
                            case ('tumblr'):
                                link = '<a  style="font-size:' + fontSize + '%" href="' + blogurl + "tagged/" + w + '" title="' + title + '">' + w + "</a>";
                                output = '<li >' + link + '</li>';
                                break;
                            case ('custom'):

                                link = '<a   style="font-size:' + fontSize + '%" href="' + blogurl + "tagged/" + w + '" title="' + title + '">' + w + "</a>";
                                if (config.classname) {
                                    output = '<li <li  class="' + config.classname + '">' + link + '</li>';
                                }

                            default:
                                link = '<a style="font-size:' + fontSize + '%" href="' + blogurl + "tagged/" + w + '" title="' + title + '">' + w + "</a>";
                                output = '<li style="display:inline;">' + link + '</li>';

                                $("#message").html(tag_count+"Tags Processed");
                        }

                        $("#tag_list").append(output);//Create list of tags in the element #tag_list

                        hiddentags++;
                        $("#bar").html(hiddentags + ":hidden tags.");




                }
            }
            $("#loading_tag_cloud").html("");var nd = new Date();var elapsed = Math.round((nd-sd) / 1000);debug(1,"Ended:"+elapsed)
        }
        $(this).attr("title", this.title+=": Starting "+sd);
        debug(1,"Started:"+sd,this);
        getUrlVars();
        GetBloginfo(config.url);

        if (typeof(config.tagged) != "undefined") {
            debug(2, "reading Tags: " + config.tagged);
            var tags = config.tagged.split(',');
            for (var i = 0; i < tags.length; i++) {
                GetPostbytags(tags[i],config.num);
            }
        }
        else if (typeof(config.postid) != "undefined")
        {
         debug(2, "reading postids: " + config.postid);
        var postids = config.postid.split(',');
        for (var i = 0; i < postids.length; i++)
        {
        GetPostbyid(postids[i]);
        }
        }else {  GetPosts();}



    });}(document));